package com.smart.wechat.login.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.smart.wechat.login.common.R;
import com.smart.wechat.login.entity.WechatUser;
import com.smart.wechat.login.mapper.WechatUserMapper;
import com.smart.wechat.login.service.IWechatUserService;
import com.smart.wechat.login.util.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信用户业务逻辑
 */
@Service
public class WechatUserServiceImpl implements IWechatUserService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${wx.oauth.appid}")
    private String APPID;

    @Value("${wx.oauth.appsecret}")
    private String APPSECRET;

    @Value("${wx.oauth.http}")
    private String HTTP;

    @Resource
    private WechatUserMapper wechatUserMapper;


    //  ====================================== 微信端 start =====================================

    /**
     * 微信授权，后端重定向url
     */
    @Override
    public String oauth() {
        // 第一步：用户同意授权，获取code
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID +
                "&redirect_uri=" + HTTP +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        logger.info("oauthRedirect：" + url);
        return "redirect:" + url;
    }
    /**
     * 回调
     */
    @Override
    public R<?> callback(String code) throws IOException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
                "&secret=" + APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        logger.info("微信登录回调请求url:{}", url);
        JSONObject jsonObject = HttpClientUtils.doGet(url);
        String openId = jsonObject.getString("openid");
        String access_Token = jsonObject.getString("access_token");
        logger.info("微信登录回调请求url的Object:{}", jsonObject);
        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token +
                "&openid=" + openId +
                "&lang=zh_CN";
        //请求微信平台
        JSONObject userInfoJson = HttpClientUtils.doGet(url);
        logger.info("微信登录回调用户信息Object:{}", userInfoJson);
        //获取微信头像
        logger.info("微信登录回调用户头像get:{}", userInfoJson.get("headimgurl"));
        String headimgurl = String.valueOf(userInfoJson.get("headimgurl"));

        //TODO 可以增加自己的逻辑，关联业务相关数据
        //TODO 可以增加自己的逻辑，关联业务相关数据
        //TODO 可以增加自己的逻辑，关联业务相关数据
        //TODO 可以增加自己的逻辑，关联业务相关数据

        Map<String, Object> result = new HashMap<>();
        result.put("token", "token");
        return R.success(result, "登录成功");

    }
    /**
     * 微信授权，前端请求url
     */
    @Override
    public R<?> getOauthUrl() {
        // 第一步：用户同意授权，获取code
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID +
                "&redirect_uri=" + HTTP +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        logger.info("oauth.url:{}",  url);
        return R.success(url, "调用授权");
    }
    /**
     * 通过code获取openId
     */
    @Override
    public R<?> getOpenIdByCode(String code) throws IOException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
                "&secret=" + APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        logger.info("通过code获取openId请求url：" + url);
        JSONObject jsonObject = HttpClientUtils.doGet(url);
        String openId = jsonObject.getString("openid");
        logger.info("通过code获取openId接口Object:{}", jsonObject.toJSONString());
        // 获取用户信息
        String access_Token = jsonObject.getString("access_token");
        logger.info("微信登录回调请求url的Object:{}", jsonObject);
        // 拉取用户信息(需scope为 snsapi_userinfo)
        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token +
                "&openid=" + openId +
                "&lang=zh_CN";
        //请求微信平台
        JSONObject userInfoJson = HttpClientUtils.doGet(url);
        logger.info("微信登录回调用户信息Object:{}", userInfoJson);
        //汇总
        Map<String, Object> result = new HashMap<>();
        if (openId != null && !"".equals(openId)){
            result.put("openId", openId);
            return R.success(result, "获取openId成功");
        }else {
            result.put("openId", null);
            return R.failed(result, "获取openId失败");
        }
    }

    //  ====================================== 微信端 end =======================================

    /**
     * 通过openId获取微信用户信息
     */
    @Override
    public WechatUser getWechatUserByOpenId(String openId) {
        return wechatUserMapper.getWechatUserByOpenId(openId);
    }
    /**
     * 添加微信用户信息
     */
    @Override
    public int insertWechatUser(WechatUser wechatUser) {
        return wechatUserMapper.insertWechatUser(wechatUser);
    }
    /**
     * 修改微信用户信息
     */
    @Override
    public int updateWechatUser(WechatUser wechatUser) {
        return wechatUserMapper.updateWechatUser(wechatUser);
    }

}
